package com.hopu.v1.service.front.course.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.pojo.classes.CourseHomeworkRecord;
import com.hopu.v1.pojo.common.R;
import com.hopu.v1.pojo.course.FCourseHomeworkRecord;
import com.hopu.v1.service.front.course.FCourseHomeworkRecordService;
import com.hopu.v1.mapper.front.course.FCourseHomeworkRecordMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
* @author admin
* @description 针对表【t_course_homework_record(学生课程作业记录表)】的数据库操作Service实现
* @createDate 2024-10-09 20:11:28
*/
@Service
public class FCourseHomeworkRecordServiceImpl extends ServiceImpl<FCourseHomeworkRecordMapper, FCourseHomeworkRecord>
    implements FCourseHomeworkRecordService {

    @Resource
    private FCourseHomeworkRecordMapper fCourseHomeworkRecordMapper;

    /**
     * 查询布置的课后作业和学生回答（根据课程id和学生id）
     * @param courseId  课程id
     * @param studentId 学生id
     * @return
     */
    public List<FCourseHomeworkRecord> getHomeworkAndAnswers(Long courseId, Long studentId) {
        return fCourseHomeworkRecordMapper.selectHomeworkAndAnswerByCidAndSid(courseId, studentId);
    }

    /**
     * 批量更新学生作业记录（根据课程id和学生id）
     * @param courseHomeworkRecords
     */
    @Transactional
    public void updateBatchByHomeworkIdAndSId(List<FCourseHomeworkRecord> courseHomeworkRecords) {
        fCourseHomeworkRecordMapper.updateBatchByHomeworkIdAndSId(courseHomeworkRecords);
    }

    /**
     * 批量添加学生课程作业记录（根据学生id和课程id）
     *
     * @param records
     * @return
     */
    @Override
    public Object insertHomeworkBatch(List<FCourseHomeworkRecord> records) {
        for (FCourseHomeworkRecord record : records) {
            // 检查记录是否已存在
            List<FCourseHomeworkRecord> existingRecords = getRecordBySIdAndHomeworkId(record.getStudentId(), record.getHomeworkId());
            if (!existingRecords.isEmpty()){
                return R.err("学生id"+record.getStudentId()+"已提交过作业"+record.getHomeworkId()+"，不允许重复提交！");
            }
        }
        fCourseHomeworkRecordMapper.insertHomeworkBatch(records);
        return null;
    }

    /**
     * 查询学生作业记录（根据学生id和课程作业id）
     * @param studentId
     * @param homeworkId
     * @return
     */
    @Override
    public List<FCourseHomeworkRecord> getRecordBySIdAndHomeworkId(Long studentId, Long homeworkId) {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("studentId",studentId);
        map.put("homeworkId",homeworkId);
        return fCourseHomeworkRecordMapper.selectRecordBySIdAndHomeworkId(map);
    }
}




